package com.example.myone.Mapper;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.myone.Entity.Article;
import com.example.myone.Entity.ArticleCategoryEnum;
import com.example.myone.R;
import com.example.myone.Util.ImageUtils;
import com.example.myone.sql.MySQLiteHelper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class ArticleMapper {
    private static final String TABLE_NAME = "article";

    // 添加方法：插入一篇文章
    public static Article insertArticle(Context context, Article article) {
        SQLiteDatabase db = MySQLiteHelper.getWritableDatabase(context);
        ContentValues values = new ContentValues();
        values.put("title", article.title);
        values.put("author", article.author);
        values.put("category", article.category);
        values.put("introduction", article.introduction);
        values.put("author_id", article.authorId);
        values.put("content", article.content);
        values.put("cover", article.cover);
        values.put("likes", article.likes);
        values.put("create_time", article.createTime);
        long insert = db.insert(TABLE_NAME, null, values);
        article.id = (int) insert;
        return article;
    }

    // 根据文章id获取文章
    public static Article getArticleById(Context context, Integer id) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from " + TABLE_NAME + " where id = ?", new String[]{id.toString()});
        ArrayList<Article> articles = getArticles(cursor);
        return articles.isEmpty() ? null : articles.get(0);
    }

    // 根据作者id获取文章
    public static List<Article> getArticleByAuthorId(Context context, Integer userId) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from " + TABLE_NAME + " where author_id = ?  order by id desc",
                new String[]{userId.toString()});
        return getArticles(cursor);
    }

    // 根据时间获取文章
    public static List<Article> getArticleByTime(Context context, String time) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from " + TABLE_NAME + " where create_time like ? order by id desc",
                new String[]{time + "%"});
        return getArticles(cursor);
    }

    // 根据类别获取文章
    public static List<Article> getArticleByCategory(Context context, String category) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery("select * from " + TABLE_NAME + " where category like ? order by id desc", new String[]{"%" + category + "%"});
        return getArticles(cursor);
    }

    // 根据类别和时间获取文章
    public static List<Article> getArticleByCategoryAndTime(Context context, String category, String time) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from " + TABLE_NAME + " where category like ? and create_time like ? order by id desc",
                new String[]{"%" + category + "%", time + "%"});
        return getArticles(cursor);
    }

    // 根据分类获取用户点赞的文章
    public static List<Article> getLikedArticlesByCategory(Context context, Integer userId, String category) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        // 使用SQL查询获取用户点赞且属于特定分类的文章
        Cursor cursor = database.rawQuery(
                "select a.* from article a " +
                        "inner join user_article_like ual on a.id = ual.article_id" +
                        " where ual.user_id = ? and a.category like ?  order by id desc",
                new String[]{userId.toString(), "%" + category + "%"}
        );
        return getArticles(cursor);
    }

    // 获取每天的一个文章
    public static List<Article> getOneArticlePerDay(Context context) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from article a where (create_time, id) " +
                        "in ( select create_time, max(id) as max_id from article group by create_time )" +
                        " order by create_time desc, id desc",
                null);
        return getArticles(cursor);
    }


    // 检查 article 表是否有数据
    private static boolean isTableEmpty(Context context) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        try (Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + TABLE_NAME, null)) {
            cursor.moveToFirst();
            return cursor.getInt(0) == 0;
        }
    }

    // 初始化文章数据
    @SuppressLint("NewApi")
    public static void init(Context context) {
        if (!isTableEmpty(context)) return;
        System.out.printf("==> 初始化 %s 数据库数据", TABLE_NAME);
        Article article = new Article();
        readFile(context, article,R.raw.text);
        article.title = "逃脱大师";
        article.authorId = 1;
        article.author = "西小麦";
        article.introduction = "他在寻找一扇门，可以进到任何地方的门，一种真正的逃脱艺术";
        article.likes = 123;
        article.createTime = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image1);
        article.category = ArticleCategoryEnum.RADIO.getMessage();
        ArticleMapper.insertArticle(context, article);
        article.authorId = 2;
        article.author = "马晓晨";
        article.title = "一样的事";
        readFile(context, article,R.raw.text1);
        article.introduction = "感情总是隐匿于人性的迷雾，也许感觉的真实本就虚幻，旁观者雾里看花。";
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image2);
        article.category = ArticleCategoryEnum.READING.getMessage();
        ArticleMapper.insertArticle(context, article);
        article.createTime = "2024-06-02";
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image3);
        article.title = "白日梦";
        article.category = ArticleCategoryEnum.QUESTION.getMessage();
        ArticleMapper.insertArticle(context, article);
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image4);
        ArticleMapper.insertArticle(context, article);
        article.authorId = 1;
        article.author = "西小麦";
        article.title = "少年子弟";
        article.createTime = "2024-06-04";
        article.introduction = "他在寻找一扇门，可以进到任何地方的门，一种真正的逃脱艺术";
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image1);
        article.category = ArticleCategoryEnum.LONG_ARTICLE.getMessage();
        ArticleMapper.insertArticle(context, article);
        article.createTime = "2024-06-05";
        readFile(context, article,R.raw.text);
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image3);
        article.category = ArticleCategoryEnum.DAILY.getMessage();
        ArticleMapper.insertArticle(context, article);
        article.title = "米奇妙妙屋";
        article.createTime = "2024-05-05";
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image5);
        ArticleMapper.insertArticle(context, article);
        article.title = "何处是我家";
        article.introduction = "感情总是隐匿于人性的迷雾，也许感觉的真实本就虚幻，旁观者雾里看花。";
        article.createTime = "2024-05-02";
        readFile(context, article,R.raw.text1);
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image6);
        article.category = ArticleCategoryEnum.QUESTION.getMessage();
        ArticleMapper.insertArticle(context, article);
        article.title = "聊天记录";
        article.createTime = "2024-05-03";
        article.cover = ImageUtils.convertImageToBase64(context, R.drawable.article_image7);
        article.category = ArticleCategoryEnum.LONG_ARTICLE.getMessage();
        ArticleMapper.insertArticle(context, article);
    }

    private static void readFile(Context context, Article article,Integer id) {
        StringBuilder stringBuilder = new StringBuilder("\t");
        try (
                InputStream inputStream = context.getResources().openRawResource(id);
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n\t");
            }
            article.content = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("init: 初始化文章异常", "错误: " + e.getMessage());
        }
    }

    @SuppressLint("Range")
    public static ArrayList<Article> getArticles(Cursor cursor) {
        ArrayList<Article> articles = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                Article article = new Article();
                article.id = cursor.getInt(cursor.getColumnIndex("id"));
                article.title = cursor.getString(cursor.getColumnIndex("title"));
                article.author = cursor.getString(cursor.getColumnIndex("author"));
                article.category = cursor.getString(cursor.getColumnIndex("category"));
                article.introduction = cursor.getString(cursor.getColumnIndex("introduction"));
                article.cover = cursor.getString(cursor.getColumnIndex("cover"));
                article.likes = cursor.getInt(cursor.getColumnIndex("likes"));
                article.createTime = cursor.getString(cursor.getColumnIndex("create_time"));
                article.authorId = cursor.getInt(cursor.getColumnIndex("author_id"));
                article.content = cursor.getString(cursor.getColumnIndex("content"));
                articles.add(article);
            } while (cursor.moveToNext());
            cursor.close();
        }

        return articles;
    }

    // 修改文章
    public static int updateArticle(Context context, Article article) {
        SQLiteDatabase db = MySQLiteHelper.getWritableDatabase(context);
        ContentValues values = new ContentValues();
        putIfNotNull(values, "author", article.author);
        putIfNotNull(values, "title", article.title);
        putIfNotNull(values, "category", article.category);
        putIfNotNull(values, "introduction", article.introduction);
        putIfNotNull(values, "cover", article.cover);
        putIfNotNull(values, "likes", article.likes);
        putIfNotNull(values, "create_time", article.createTime);
        putIfNotNull(values, "author_id", article.authorId);
        return db.update(TABLE_NAME, values, "id=?", new String[]{String.valueOf(article.id)});
    }

    private static <T> void putIfNotNull(ContentValues values, String key, T value) {
        if (value != null) {
            values.put(key, String.valueOf(value));
        }
    }

    // 根据id删除文章
    public static int deleteArticle(Context context, int id) {
        SQLiteDatabase db = MySQLiteHelper.getWritableDatabase(context);
        return db.delete(TABLE_NAME, "id=?", new String[]{String.valueOf(id)});
    }
}
